<?php
/*
Creates an xml file based on contents of a text file for bicycle route libraries.
xml DOM format is:

<library>
    <route>
        <title></title>  
        <category></category>
        <hilliness></hilliness>
        <mileage></mileage>
        <text></text>
    </route>
    ...
</library>
*/

// adds a child node "tagName" with "text" to "parent" in "document"
function addChildWText ( $document, $parent, $tagName, $text ) {
    $newTag = $document->createElement( $tagName );
    $newTag->appendChild( $document->createTextNode( $text ));
    $parent->appendChild( $newTag );
}


$XML_FILENAME = "routelibrary.xml";         // new xml filename

$textLibrary = file_get_contents("Route Library.txt");          // text file from which data is extracted

$libArray = array();                        // store the array of routes

foreach ( preg_split('%\-{5,}\s%', $textLibrary) as $route) {

    $regExp = '%([a-f]+\/\d\/\d+)%i';       // regExp in the format of ride categorization ( e.g., C/4/23 )

	$splitArray = preg_split ( $regExp, $route ); // $splitArray[0] becomes the "title"
		   
	preg_match  ( $regExp , $route, $matches ); // separate the three elements of the ride categorization ( e.g., C/4/23 )
	$qualities = split ( '/', $matches[1] );
	
	$libArray [] = array(
	    'title' => trim( $splitArray[0] ),
	    'category' => $qualities[0],
	    'hilliness' => $qualities[1],
	    'mileage' => $qualities[2],
	    'text' => trim( $route )
	);
}


$doc = new DOMDocument();
$doc->formatOutput = true;

$library = $doc->createElement( "library" );
$doc->appendChild( $library );

// for each item in $libArray, make an xml tag with appropriate children
foreach( $libArray as $route ) {
    
    $newRoute = $doc->createElement( "route" );  // create a new route tagname
    
    addChildWText( $doc, $newRoute, "title", $route[ 'title' ]);
    addChildWText( $doc, $newRoute, "category", $route[ 'category' ]);
    addChildWText( $doc, $newRoute, "hilliness", $route[ 'hilliness' ]);
    addChildWText( $doc, $newRoute, "mileage", $route[ 'mileage' ]);
    addChildWText( $doc, $newRoute, "text", $route[ 'text' ]);
    
    $library->appendChild( $newRoute );
}

echo $doc->save( $XML_FILENAME );
?>
